package com.javacv.plus.extensions.audio.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.audio.AudioProcessor;
import com.javacv.plus.extensions.audio.AudioResult;
import com.javacv.plus.extensions.audio.config.AudioConfig;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;

/**
 * 保存音频步骤
 */
@Slf4j
public class SaveAudioStep implements ProcessorStep<AudioProcessor, AudioResult> {
    @Override
    public AudioResult execute(AudioProcessor processor, ProcessorContext context) throws Exception {
        String outputPath = processor.getConfig().getOutputPath();
        log.info("Saving audio to: {}", outputPath);

        FFmpegFrameGrabber grabber = (FFmpegFrameGrabber) context.getAttribute("grabber");
        AudioConfig config = processor.getAudioConfig();

        try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
                outputPath,
                config.isKeepOriginalChannels() ? grabber.getAudioChannels() : config.getChannels(),
                config.isKeepOriginalSampleRate() ? grabber.getSampleRate() : config.getSampleRate()
        )) {
            // 设置音频参数
            recorder.setFormat(config.isKeepOriginalFormat() ? grabber.getFormat() : config.getFormat());
            recorder.setAudioBitrate(config.isKeepOriginalBitRate() ? grabber.getAudioBitrate() : config.getBitRate());
            recorder.setAudioChannels(config.isKeepOriginalChannels() ? grabber.getAudioChannels() : config.getChannels());
            recorder.setSampleRate(config.isKeepOriginalSampleRate() ? grabber.getSampleRate() : config.getSampleRate());

            recorder.start();

            // 处理音频帧
            while (true) {
                Frame frame = grabber.grab();
                if (frame == null) {
                    break;
                }
                recorder.record(frame);
            }
        }

        log.info("Audio saved successfully");
        return null;
    }

    @Override
    public String getStepName() {
        return "SaveAudio";
    }
} 